package excelUtils

import (
	"fmt"
	"github.com/xuri/excelize/v2"
	"go-demo-2025/common"
	"io/fs"
	"os"
	"time"
)

var filePath string

func init() {
	filePath = fmt.Sprintf("files/%s", time.Now().Format("2006/01/02/"))
}

// 文档: https://xuri.me/excelize/zh-hans/

// WriteExcel 导出 Excel 文档
// data: 要导出的数据
// return: 文件名, error
func WriteExcel(data [][]string, relativePath string, fileName string) (string, error) {
	//创建存放目录
	relativeFilePath := filePath + relativePath + "/"
	_, err := os.ReadDir(relativeFilePath)
	if err != nil {
		// 不存在就创建
		err = os.MkdirAll(relativeFilePath, fs.ModePerm)
		if err != nil {
			fmt.Println(err)
		}
	}

	//创建表格
	file := excelize.NewFile()
	sheetName := "Sheet1"
	index, _ := file.NewSheet(sheetName)
	for i, row := range data {
		for j, val := range row {
			// 列和行 数字索引转excel坐标索引
			cellName, _ := excelize.CoordinatesToCellName(j+1, i+1)
			//fmt.Println("cellName:", cellName)
			// 写入sheet
			file.SetCellValue(sheetName, cellName, val)
		}
	}
	file.SetActiveSheet(index)

	//导出文件
	filePathName := relativeFilePath + fileName + "_" + common.GetMicroTimestamp() + ".xlsx"
	err = file.SaveAs(filePathName)
	if err != nil {
		return "", err
	}
	return filePathName, nil
}

// 根据自定义的二维切片,封装导出的表头字段的key和title
func GetDataKeyAndTitle(dataKeySlice [][]string) ([]string, []string) {
	//自定义导出的字段
	var dataKeys []string
	var dataKeysTitle []string

	if len(dataKeySlice) > 0 { //如果定义了key对应的字段值
		for _, v := range dataKeySlice {
			if len(v[1]) > 0 {
				dataKeysTitle = append(dataKeysTitle, v[1])
			} else if len(v[0]) > 0 {
				dataKeysTitle = append(dataKeysTitle, v[0])
			}

			if len(v[0]) > 0 {
				dataKeys = append(dataKeys, v[0])
			}
		}
	}
	return dataKeys, dataKeysTitle
}

// 读取 Excel 文档
func ReadExcel() {
	f, err := excelize.OpenFile("Book1.xlsx")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	// 获取工作表中指定单元格的值
	cell, err := f.GetCellValue("Sheet1", "B2")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(cell)
	// 获取 Sheet1 上所有单元格
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, row := range rows {
		for _, colCell := range row {
			fmt.Print(colCell, "\t")
		}
		fmt.Println()
	}
}
